package com.xxx.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xxx.pojo.*;
import com.xxx.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.plugin.extension.ExtensionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  员工查询
 * </p>
 *
 * @author WXH
 * @since 2022-02-23
 */
@RestController
//RequestMapping：用于处理请求 url 映射的注解，可用于类或方法上。用于类上，则表示类中
//的所有响应请求的方法都是以该地址作为父路径。
@RequestMapping("/employee/basic")
@Api(value = "员工管理", tags = "员工管理")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    IPoliticsStatusService iPoliticsStatusService;

    @Autowired
    IJoblevelService iJoblevelService;

    @Autowired
    INationService iNationService;

    @Autowired
    IPositionService iPositionService;

    @Autowired
    IDepartmentService iDepartmentService;

//    @ApiOperation(value = "获取所有员工信息（分页22）")
////    @GetMapping("/list")
////    public RespPageBean getEmloyee22(@RequestParam(required = false) Integer currentPage,
////                                    @RequestParam(required = false) Integer size,
////                                    Employee employee,
////                                    LocalDate[] beginDateScope){
////        return employeeService.getEmployeeByPage22(currentPage,size,employee,beginDateScope);
////    }


    @ApiOperation(value = "获取所有员工信息（分页）")
    @GetMapping("/list")
    public RespPageBean getEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                    @RequestParam(defaultValue = "10") Integer size,
                                    Employee employee,
                                    LocalDate[] beginDateScope){
        return employeeService.getEmployeeByPage(currentPage,size,employee,beginDateScope);
    }
    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/get-politics-status")
    public List<PoliticsStatus> getPliticsStatus(){
        return iPoliticsStatusService.list();
    }
    @ApiOperation(value = "获取所有职称")
    @GetMapping("/get-all-job")
    public List<Joblevel> getJoblevel() {

        return iJoblevelService.list();
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/get-all-Nation")
    public List<Nation> getNation() {

        return iNationService.list();
    }

    @ApiOperation(value = "获取所有岗位")
    @GetMapping("/get-all-Position")
    public List<Position> getPosition() {

        return iPositionService.list();
    }

    @ApiOperation(value = "获取所有部门")
    @GetMapping("/get-all-Department")
    public List<Department> Department() {

        return iDepartmentService.list();
    }
    @ApiOperation(value = "获取最大工号方法一")
    @GetMapping("/get-max-WorkID")
    public RespBean getMaxWorkID1() {
        //工号为char类型 获取工号后 +1 可以保证ID自增并且唯一
        return employeeService.getMaxWorkID();
    }

    @ApiOperation(value = "获取最大工号方法二")
    @GetMapping("/get-max-WorkID2")
    public RespBean getMaxWorkID2() {
        //工号为char类型 获取工号后 +1 可以保证ID自增并且唯一
        return employeeService.getMaxWorkID2();
    }

    @ApiOperation(value = "添加员工")
    @PostMapping("/addEmp")
//    @RequestBody：注解实现接收http请求的json数据，将json转换为java对象。
    public RespBean addEmp(@RequestBody Employee employee) {
        RespBean bean = employeeService.addEmp(employee);
        return bean;
    }

    @ApiOperation(value = "更新员工")
    @PutMapping("/update")
    public RespBean updateEmp(@RequestBody Employee employee) {
        if (employeeService.updateById(employee)) {
            return RespBean.sucess("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation(value = "删除员工")
    @DeleteMapping("/delete/{id}")
    public RespBean deleteEmp(@PathVariable Integer id) {
        if (employeeService.removeById(id)) {
            return RespBean.sucess("删除成功！");

        }
        return RespBean.error("删除失败！");
    }
    @ApiOperation(value = "导出员工数据")
    //没有produces会乱码
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        List<Employee> list = employeeService.getEmployee(null);
        ExportParams parms = new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(parms, Employee.class, list);
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode("员工表.xls","UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭流
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @ApiOperation(value = "导入员工数据")
    @PostMapping("/import")
    public RespBean importEmphasis(MultipartFile multipartFile) {
        ImportParams params = new ImportParams();
        //表的标题行数，去掉前两行(第一行表标题，第二行列标题)，如果超出表格本身的标题行数，截取数据为null
        params.setTitleRows(1);
        //列标题和实际字段值的距离，可以设置从第几行开始截取数据，默认为0，就是列标题的下一行
        //params.setStartRows(0);
        List<Nation> nationList = iNationService.list();
        List<Department> departmentList = iDepartmentService.list();
        List<Joblevel> joblevelList = iJoblevelService.list();
        List<PoliticsStatus> politicsStatusList = iPoliticsStatusService.list();
        List<Position> positionList = iPositionService.list();
        try {
            List<Employee> employeeList = ExcelImportUtil.importExcel(multipartFile.getInputStream(), Employee.class, params);
            employeeList.forEach(employee -> {
                /**
                 * 思想是将民族的转化为hashcode再和已有的作比较
                 * */
                //民族id
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                //政治面貌id
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                //部门id
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
                //职称id
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                //职位id
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
            });
            if(employeeService.saveBatch(employeeList)){
                return RespBean.sucess("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");

    }


}
